
//  HBAddBankCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/11/30.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBAddBankCtrl.h"
#import "HBBankListCtrl.h"
#import "CheckValid.h"
#import "HBInvestCtrl.h"
#import "HBInvestSuccessCtrl.h"
#import "CustomerCardOwner.h"
#import "CustomerPhoneNum.h"
#import "CustomerBankCardSuc.h"
#import "HBGetUserInfoManager.h"
#import "HBInvestFailedCtrl.h"
#import "HBLoginManager.h"
#import "HBLoginUserInfo.h"
#import "HBBindBankCardAndInvestInfo.h"
#import "HBBindBankCardAndInvestParam.h"
#import "HBBindBankCardAndInvestParser.h"
#import "HBUserInvestInfo.h"
#import "HBUserInvestParam.h"
#import "HBUserInvestParser.h"
#import "HBUserConfirmInvestInfo.h"
#import "HBUserConfirmInvestParam.h"
#import "HBUserConfirmInvestParser.h"
#import "HBBindBankCardInfo.h"
#import "HBBindBankCardParam.h"
#import "HBBindBankCardParser.h"
#import "HBBindBankCardConfirmParam.h"
#import "HBBindBankCardConfirmParser.h"
#import "HBUserDistillInfo.h"
#import "HBUserDistillParam.h"
#import "HBUserDistillParser.h"
#import "HBWithdrawCtrl.h"
#import "HBInvestManager.h"

@interface HBAddBankCtrl ()<UITextFieldDelegate>
{
    NSArray*     fieldArr;
    UITextRange* previousSelection;
    NSString*    previousTextFieldContent;
    NSString*    bankCardNum;
    CGFloat      midViewNormalH;
    CGFloat      midViewAddPhoneH;
    NSString*    cardValidToken;
    HBBindBankCardAndInvestInfo* bindInfo;
}
- (IBAction)cardNumBtn:(UIButton *)sender;

//获取个人身份认证
- (IBAction)selectBank:(UIButton *)sender;
- (IBAction)getVercode:(UIButton *)sender;
- (IBAction)changCardNum:(UIButton *)sender;
- (IBAction)userNameList:(UIButton *)sender;
- (IBAction)confirmClicked:(UIButton *)sender;
@property (strong, nonatomic) NSString* bankcode;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *botView;
@property (weak, nonatomic) IBOutlet UIView *mainView;

@property (weak, nonatomic) IBOutlet UILabel *alertLabel;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *getVerCodeBtn;
@property (weak, nonatomic) IBOutlet UITextField *cardNumField;
@property (weak, nonatomic) IBOutlet UITextField *verCodeField;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumfield;
@property (weak, nonatomic) IBOutlet UITextField *bankStyleField;
@property (weak, nonatomic) IBOutlet UITextField *identificationCard;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *botViewH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *midViewH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardFieldW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *alertLabelH;
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardNumViewH;

@property (nonatomic, strong) HBBindBankCardAndInvestInfo *bindInvestInfo;

@end

//有两个调用该页面，投资，绑定
@implementation HBAddBankCtrl

#define GetFinalresult(a,b) (IsIphone4?a:b)
#define kAlphaNum @"Xx0123456789"
#define kOnlyNum @"0123456789"
#define K_ABC @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmwopqrstuvwxyz"

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self makeTime];
//    [self setLeftButtonNull];
    [self setTextFieldTextEmpty];
    
    //是否实名认证，是否显示身份证号码栏
    if (self.isRealName == YES) {
        self.cardNumViewH.constant = 0;
        self.nameField.enabled = NO;
        midViewNormalH = 132;
        midViewAddPhoneH = 220;
        self.identificationCard.text = @"";//已经绑定不必传身份证
        self.nameField.text = [HBLoginManager sharedHBLoginManager].currentUserInfo.username;
    }else if(self.isRealName == NO){
        self.cardNumViewH.constant = 44;
        midViewNormalH = 176;
        midViewAddPhoneH = 264;
    }
   
    [self setAppearWithObject:self.botView hidden:YES];
}

- (void)setTextFieldTextEmpty{
    self.cardNumField.text = @"";
    self.verCodeField.text = @"";
    self.phoneNumfield.text = @"";
    
    }
- (void)setTextFieldInitialization{
    self.cardNumField.delegate = self;
    self.verCodeField.delegate = self;
    self.phoneNumfield.delegate = self;
    self.identificationCard.delegate = self;
    
    [self.cardNumField setKeyboardType:UIKeyboardTypeNumberPad];
    [self.verCodeField setKeyboardType:UIKeyboardTypeNumberPad];
    [self.phoneNumfield setKeyboardType:UIKeyboardTypeNumberPad];
    [self.identificationCard setKeyboardType:UIKeyboardTypeASCIICapable];
   
    [self.nameField addTarget:self action:@selector(textFieldEdit:) forControlEvents:UIControlEventEditingChanged];
    [self.identificationCard addTarget:self action:@selector(textFieldEdit:) forControlEvents:UIControlEventEditingChanged];
    [self.cardNumField addTarget:self action:@selector(textFieldEdit:) forControlEvents:UIControlEventEditingChanged];
    [self.phoneNumfield addTarget:self action:@selector(textFieldEdit:) forControlEvents:UIControlEventEditingChanged];
    [self.verCodeField addTarget:self action:@selector(textFieldEdit:) forControlEvents:UIControlEventEditingChanged];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nameFiledChanged:) name:UITextFieldTextDidChangeNotification object:self.nameField];
    
    if (self.isRealName == YES) {
        fieldArr = @[self.nameField,self.bankStyleField,self.cardNumField, self.cardNumField,self.phoneNumfield,self.verCodeField];
    }else{
        fieldArr = @[self.nameField, self.identificationCard,self.bankStyleField,self.cardNumField, self.cardNumField,self.phoneNumfield,self.verCodeField];
    }
       for (int i =0; i <fieldArr.count; i ++) {
        [self setTextFieldPlaceHolder:fieldArr[i]];
    }
    if (IsIphone4 ||IsIphone5)
    {
        self.cardFieldW.constant = 170;
        self.cardNumField.font = [UIFont systemFontOfSize:13];
    }
    else
    {
        self.cardFieldW.constant = 180;
    }
}

- (void)nameFiledChanged:(NSNotification*) notification{
    if(![self.nameField.text isEqualToString:@""]){
        for (int i=0; i<self.nameField.text.length; i++) {
            NSRange range=NSMakeRange(i,1);
            NSString *subString=[self.nameField.text substringWithRange:range];
            //如果是表情符号，就返回空
            subString = [self disable_emoji:subString];
            if(self.nameField.text.length>20){
//                self.nameField.text = @"";
                self.nameField.placeholder = @"请输入您的姓名";
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"\"姓名\"输入过长,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alertView.tag = 3000;
                [alertView show];
                [self resignKeyboard];
                return;
            }
        }
    }
}
- (void)resignKeyboard{
    [self.view endEditing:YES];
}
//禁止输入表情符号
- (NSString *)disable_emoji:(NSString *)text{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text
                                                               options:0
                                                                 range:NSMakeRange(0, [text length])
                                                          withTemplate:@""];
    return modifiedString;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)buildLayout{
    self.title = @"添加银行卡";
    [self showDoneWithTitle:@"取消"];
    
    self.botView.alpha = 0;
    self.botViewH.constant = 0;
    self.getVerCodeBtn.layer.cornerRadius = 4;
    [self.confirmBtn.layer setMasksToBounds:YES];
    [self.confirmBtn.layer setCornerRadius:4.0];
    [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"d43333"] forState:UIControlStateHighlighted];
    [self setTextFieldInitialization];
}

- (void)doDone{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)setLeftButtonNull{
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    if (self.navigationController.viewControllers[0] != self) {
        self.navigationItem.leftBarButtonItem = leftItem;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)setTextFieldPlaceHolder:(UITextField*)textField  {
    if (isIphone4or5) {
        textField.font = [UIFont systemFontOfSize:14];
    }else{
        textField.font = [UIFont systemFontOfSize:15];
    }
    textField.textColor = [LCCommon getColor:@"ffffff"];
    [textField setValue:[LCCommon getColor:@"5e5e5f"] forKeyPath:@"_placeholderLabel.textColor"];
}

#pragma mark -TextField Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;

    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.cardNumField == textField){
        if ([string length] > 0) {
            self.cardNumField.text = [self bankCardFormat:self.cardNumField.text];
        }
        if ([toBeString length] > 15){
            [self setAppearWithObject:self.botView hidden:NO];
            if ([toBeString length] > 22) {
                textField.text = [toBeString substringToIndex:23];
                [textField resignFirstResponder];
                return NO;
            }
        }
    }
    if (self.phoneNumfield == textField) {
        if ([toBeString length] >10) {
            textField.text = [toBeString substringToIndex:11];
            [textField resignFirstResponder];
            return NO;
        }
    }
    if (self.verCodeField == textField){
        [self checkFieldTextAndVerCodeCheck:NO];
        if ([toBeString length] >5) {
            [self.confirmBtn setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
            [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"bd3737"]];
            textField.text = [toBeString substringToIndex:6];
            [textField resignFirstResponder];
            return NO;
        }
    }
    //身份证号
    NSCharacterSet *cs;
    if (textField == self.identificationCard) {
        if ([toBeString length]<=17) {
            cs = [[NSCharacterSet characterSetWithCharactersInString:kOnlyNum] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
            BOOL canChange = [string isEqualToString:filtered];
            return self.identificationCard.text.length>19?NO: canChange;
        }else if([toBeString length] >17 && [toBeString length]<= 18){
            NSCharacterSet *cs;
            cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
            BOOL canChange = [string isEqualToString:filtered];
            return self.identificationCard.text.length>19?NO: canChange;
        }else if ([toBeString length] > 18) {
            return NO;
        }
    }
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0 - 88);//键盘高度216
    LLog(@"offset ----- %d",offset);
    if (textField == self.phoneNumfield ){
        offset = GetFinalresult(88, 0);
    }else if(textField == self.verCodeField){
        offset = GetFinalresult(120, 20);
    }else if(textField == self.bankStyleField){
        offset = GetFinalresult(40, 0);
    }
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    //视图Y坐标向上移offset
    if(offset > 0 )
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}
//按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
//恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.cardNumField resignFirstResponder];
    [self.phoneNumfield resignFirstResponder];
    [self.verCodeField resignFirstResponder];
    [self.nameField resignFirstResponder];
    [self.identificationCard resignFirstResponder];
    self.view.frame =CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
}

#pragma BankFormat
- (NSString *)bankCardFormat:(NSString *)string{
    NSString *result = nil;
    NSString *space = @" ";
    NSMutableString *mutableString = [[NSMutableString alloc] init];
    [mutableString appendString:string];
    NSInteger stringLength = [mutableString length];
    if (stringLength >= 4) {
        if (stringLength%5 == 0) {
            [mutableString insertString:space atIndex:stringLength-1];
        }
        result = mutableString;
    }else{
        result = mutableString;
    }
    return result;
}

- (BOOL)checkFieldTextAndVerCodeCheck:(BOOL)check{
    for (UITextField* textField in fieldArr) {
        BOOL isEmpty = [CheckValid checkStrIsEmpty:textField.text];
        if (isEmpty == YES) {
           [self setAppearWithObject:self.alertLabel hidden:NO];
            [textField becomeFirstResponder];
            NSString* alertString;
            if (textField == self.nameField) {
                alertString = @"请输入您的姓名";
            }
            if (textField == self.identificationCard) {
                if (self.isRealName == NO){
                   alertString = @"请输入您的身份证号码";
                }
            }
            if (textField == self.bankStyleField) {
                alertString = @"请先选择银行";
            }
            if (textField == self.cardNumField) {
                alertString = @"请输入银行卡卡号";
            }
            if (textField == self.phoneNumfield) {
                alertString = @"请输入手机号码";
            }
            if (textField == self.verCodeField) {
                if (check == YES) {
                    if (textField == self.verCodeField) {
                        alertString = @"请输入验证码";
                    }
                }else{
                     [self setAppearWithObject:self.alertLabel hidden:YES];
                }
            }
            self.alertLabel.text = alertString;
            [textField becomeFirstResponder];
            LLog(@"%@",self.alertLabel.text);
            return NO;
        }else{
            if (textField == self.nameField) {
                if ([CheckValid IsChinese:self.nameField.text] == NO) {
                    [self setAppearWithObject:self.alertLabel hidden:NO];
                    [self.alertLabel setText:@"请输入您的中文姓名"];
//                    self.nameField.text = @"";
                    return NO;
                }
            }
            
            if (textField == self.identificationCard) {
                LLog(@"%@",self.identificationCard.text);
                //只能验证位数
                if (![CheckValid isValidateIdentityCard:self.identificationCard.text]){
                    [self setAppearWithObject:self.alertLabel hidden:NO];
                    self.alertLabel.text = @"请输入正确的身份证号码";
//                    [self.identificationCard setText:@""];
                    [self.identificationCard becomeFirstResponder];
                    return NO;
                }
            }
            
            if (textField == self.phoneNumfield) {
                if (![CheckValid isValidatePhone:self.phoneNumfield.text]) {
                    [self setAppearWithObject:self.alertLabel hidden:NO];
                    self.alertLabel.text = @"手机号输入不正确";
                    self.phoneNumfield.text = @"";
                    self.verCodeField.text = @"";
                    [self.phoneNumfield becomeFirstResponder];
                    return NO;
                }
            }
            
            
        }
    }
    return YES;
}

- (IBAction)confirmClicked:(UIButton *)sender {
    [self.confirmBtn setBackgroundColor:[LCCommon getColor:@"d43333"] forState:UIControlStateHighlighted];
    BOOL isEmpty = [self checkFieldTextAndVerCodeCheck:YES];
    if (isEmpty == NO) {
        return;
    }else{
        [self requestBindBankCard];
    }
}


-(void)pushNext{
    UIViewController* VC ;
    switch (self.viewpageJumpingFrom) {
        case isFromBankView:
            [self.navigationController popToRootViewControllerAnimated:YES];
            break;
        case isFromInvestView:
             VC = [[HBInvestCtrl alloc] init];
             [self.navigationController pushViewController:VC animated:YES];
            break;
    }
}

- (IBAction)userNameList:(UIButton *)sender {
    if(sender.tag == 1000){
        LLog(@"持卡人说明");
        [[[CustomerCardOwner alloc] initCardOwner] showInView];
    }else if(sender.tag == 1001){
        LLog(@"手机号说明");
         [[[CustomerPhoneNum alloc] initPhNum] showInView];
    }
}

- (IBAction)selectBank:(UIButton *)sender {
    HBBankListCtrl* bankListVC = [[HBBankListCtrl alloc] init];
    bankListVC.userName = self.nameField.text;
    
    bankListVC.bankBlock = ^(NSString* bankName,NSString* bankCode,NSString* userNam){
        if (![bankName isEqualToString:@""]) {
            self.bankStyleField.text = bankName;
            self.bankcode = bankCode;
            self.nameField.text = userNam;
        }
    };
    [self.navigationController pushViewController:bankListVC animated:YES];
}

- (IBAction)changCardNum:(UIButton *)sender {
    
    self.cardNumField.text = @"";
    self.phoneNumfield.text = @"";
    self.verCodeField.text = @"";
    [self setAppearWithObject:self.botView hidden:YES];
    [self setAppearWithObject:self.alertLabel hidden:YES];
}

- (IBAction)getVercode:(UIButton *)sender {
    self.verCodeField.text = @"";
    [self checkFieldTextAndVerCodeCheck:NO];
    if (![CheckValid isValidatePhone:self.phoneNumfield.text]) {
        [self setAppearWithObject:self.alertLabel hidden:NO];
        self.alertLabel.text = @"手机号输入不正确";
//        self.phoneNumfield.text = @"";
//        self.verCodeField.text = @"";
        [self.phoneNumfield becomeFirstResponder];
        return;
    }
    //判断从哪个页面过来
    if (self.viewpageJumpingFrom == isFromInvestView ) {
        [self requestGetVerCodeBindCardFromBindView];
    }else if(self.viewpageJumpingFrom == isFromBankView){
        [self requestGetVerCodeBindCardFromBindView];
    }
}
- (void)requestGetVerCodeBindCardFromBindView{
    HBBindBankCardParam* param = [[HBBindBankCardParam alloc] init];
    HBBindBankCardParser* parser = [[HBBindBankCardParser alloc] init];
    HBLoginUserInfo* LoginInfo = [HBLoginManager sharedHBLoginManager].currentUserInfo;
    param.uid = LoginInfo.uid;
    param.token = LoginInfo.token;
    param.username = self.nameField.text;
    param.idCardno = self.identificationCard.text;
    param.bankCode = self.bankcode;
    param.bankName = self.bankStyleField.text;
    param.bankCardno = [self.cardNumField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    param.accountMobile = self.phoneNumfield.text;
    [CustomLoadingView showHudToView:self.view];
    [NetCenter postDataFromURL:Method_bindBankCard params:param parser:parser result:^(ParserResult *myResult) {
        [self setTimerDefault];
        
        if (myResult.code == 0) {
            HBBindBankCardInfo* info = (HBBindBankCardInfo*)myResult.result;
            LLog(@"验证码已发送");
           [self makeTime];
            cardValidToken = info.cardValidToken;

        }else{
            [self setAppearWithObject:self.alertLabel hidden:NO];
            self.alertLabel.text = myResult.message;
            DISSMISS_ERR(myResult.message);
        }
        [CustomLoadingView hideHudForView:self.view];
    } failure:^(NSError *error) {
        [self setAppearWithObject:self.alertLabel hidden:NO];
        [CustomLoadingView hideHudForView:self.view];
        self.alertLabel.text = error.description;
        DISSMISS_ERR(error.description);
    }];
}

- (void)setTimerDefault{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 60] forKey:ADDBANKCARD_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)requestGetVerCodeBindCardFromInvestView{
    HBBindBankCardAndInvestParam* param = [[HBBindBankCardAndInvestParam alloc] init];
    HBBindBankCardAndInvestParser* parser = [[HBBindBankCardAndInvestParser alloc] init];
    HBLoginUserInfo* LoginInfo = [HBLoginManager sharedHBLoginManager].currentUserInfo;
    
    param.uid = LoginInfo.uid;
    param.token =LoginInfo.token;
    param.username = self.nameField.text;
    param.idCardno = self.identificationCard.text;
    param.bankCode = self.bankcode;
    param.bankName = self.bankStyleField.text;
    param.bankCardno = self.cardNumField.text;
    param.bankCardno = [param.bankCardno stringByReplacingOccurrencesOfString:@" " withString:@""];
    param.accountMobile = self.phoneNumfield.text;
    param.investMoney = self.investMoney;
    
    [NetCenter postDataFromURL:Method_bindBankCardAndInvest params:param parser:parser result:^(ParserResult *myResult) {
        [self setTimerDefault];
        [self makeTime];
        if (myResult.code == 0) {
            bindInfo = (HBBindBankCardAndInvestInfo*)myResult.result;
            self.bindInvestInfo = bindInfo;
            
            
        }else if(myResult.code == 1){
//            DISSMISS_ERR(myResult.message);
            [self setAppearWithObject:self.alertLabel hidden:NO];
            self.alertLabel.text = myResult.message;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                for (UIViewController *popctrl in self.navigationController.viewControllers) {
                    if ([popctrl isKindOfClass:[HBInvestCtrl class]]) {
                        [self.navigationController popToViewController:popctrl animated:YES];
                        break;
                    }
                }
            });
        }
    } failure:^(NSError *error) {
//        DISSMISS_ERR(error.description);
        [self setAppearWithObject:self.alertLabel hidden:NO];
        self.alertLabel.text = error.description;
    }];
    
}
#pragma DistillInfo
//从提现页面过来 点击 确定时候
-(void)requestToGetDistillInfo{
    [CustomLoadingView showHudToView:self.view];
    HBUserDistillParam *param = [[HBUserDistillParam alloc]init];
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    HBUserDistillParser *parser = [[HBUserDistillParser alloc]init];
    [NetCenter postDataFromURL:Method_userDistill params:param parser:parser result:^(ParserResult *myResult) {
//        [CustomLoadingView hideHudForView:self.view];
//        if (myResult.code == 0)
//        {
//            HBUserDistillInfo *info = (HBUserDistillInfo *)myResult.result;
//            HBInvestCtrl* distillVC = [[HBInvestCtrl alloc] init];
//            [self.navigationController pushViewController:distillVC animated:YES];
//        }
//        else
//        {
//            DISSMISS_ERR(myResult.message);
//        }
        
           } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
    }];
    
}

//从投资页面过来 点击 确定时候
- (void)requestConFirmInvest{
    HBUserConfirmInvestParam* param = [[HBUserConfirmInvestParam alloc] init];
    HBUserConfirmInvestParser* parser = [[HBUserConfirmInvestParser alloc] init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.orderBillCode = bindInfo.orderBillCode;
    param.orderBillToken = bindInfo.orderBillToken;
    if (self.bindInvestInfo)
    {
        param.orderBillCode = self.bindInvestInfo.orderBillCode;
        param.orderBillToken = self.bindInvestInfo.orderBillToken;
    }
    param.investMobileCode = self.verCodeField.text;
    
    [NetCenter postDataFromURL:Method_userConfirmInvest params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            HBUserConfirmInvestInfo* confirmInvInfo = (HBUserConfirmInvestInfo*)myResult.result;
            if ([confirmInvInfo.investStatus integerValue]==0)
            {
                HBInvestSuccessCtrl *investSuccessCtrl = [[HBInvestSuccessCtrl alloc]initWithNibName:NSStringFromClass([HBInvestSuccessCtrl class]) bundle:nil];
                investSuccessCtrl.confirmInvestInfo = confirmInvInfo;
                [self.navigationController pushViewController:investSuccessCtrl animated:YES];
            }
            else
            {
                HBInvestFailedCtrl *investFailedCtrl = [[HBInvestFailedCtrl alloc]init];
                investFailedCtrl.confirmInvestInfo = confirmInvInfo;
                [self.navigationController pushViewController:investFailedCtrl animated:YES];
            }

        }else{
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
       DISSMISS_ERR(error.description);
    }];
}
//绑定银行卡
- (void)requestBindBankCard{
    
    HBBindBankCardConfirmParam* param = [[HBBindBankCardConfirmParam alloc] init];
    HBBindBankCardConfirmParser* parser = [[HBBindBankCardConfirmParser alloc] init];
    HBLoginUserInfo* LoginInfo = [HBLoginManager sharedHBLoginManager].currentUserInfo;
    
    param.uid = LoginInfo.uid;
    param.token =LoginInfo.token;
    param.username = self.nameField.text;
    param.idCardno = self.identificationCard.text;
    param.bankCode = self.bankcode;
    param.bankName = self.bankStyleField.text;
    param.bankCardno = self.cardNumField.text;
    param.bankCardno = [param.bankCardno stringByReplacingOccurrencesOfString:@" " withString:@""];
    param.accountMobile = self.phoneNumfield.text;
    param.cardValidCode = self.verCodeField.text;
    if (cardValidToken) {
        param.cardValidToken = cardValidToken;
    }
    [ CustomLoadingView  showHudToView:self.view];
    [NetCenter postDataFromURL:Method_bindBankCardConfirm params:param parser:parser result:^(ParserResult *myResult) {
       
        HBUserConfirmInvestInfo* confirmInvInfo = (HBUserConfirmInvestInfo*)myResult.result;
        if (myResult.code == 0) {
            LLog(@"绑定成功");
            [HBGetUserInfoManager requestToGetUserInfoWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
            [self requestBankCardInformationWithBankName:self.bankStyleField.text bankCard:self.cardNumField.text];
            [ CustomLoadingView  hideHudForView:self.view];
        }else{
            [ CustomLoadingView  hideHudForView:self.view];
            DISSMISS_ERR(myResult.message);
            
        }
    } failure:^(NSError *error) {
        [ CustomLoadingView  hideHudForView:self.view];
        DISSMISS_ERR(error.description);
    }];

}
//
- (void)requestBankCardInformationWithBankName:(NSString*)bankName bankCard:(NSString*)bankCard{
    [CustomLoadingView showHudToView:self.view];
    [HBInvestManager requestToGetUserInvestLimitWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
        //        [CustomLoadingView hideHudForView:nil];
        [CustomLoadingView hideHudForView:self.view];
        if (isSuccess)
        {
            if (self.viewpageJumpingFrom == isFromBankView) {
                CustomerBankCardSuc* bindSucVC = [[CustomerBankCardSuc alloc] initWithBankName:bankName withBankCard:bankCard];
                [bindSucVC showInView];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
                
            }else if(self.viewpageJumpingFrom == isFromInvestView){
                HBInvestCtrl *investCtrl = [[HBInvestCtrl alloc]init];
                [self.navigationController pushViewController:investCtrl animated:YES];
            }
            
        }
        else
        {
            DISSMISS_ERR(error?[error description]:msg);
        }
    }];

}

- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:ADDBANKCARD_CODE_TIME] longLongValue];
        if (timeLast <= 0){
            self.getVerCodeBtn.enabled = YES;
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
            [self.getVerCodeBtn setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
            self.getVerCodeBtn.backgroundColor = [LCCommon getColor:@"F24545"];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            self.getVerCodeBtn.enabled = YES;
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            [self.getVerCodeBtn setTitle:@"获取验证码" forState:UIControlStateDisabled];
            [self.getVerCodeBtn setTitleColor:[LCCommon getColor:@"ffffff"] forState:UIControlStateNormal];
            self.getVerCodeBtn.backgroundColor = [LCCommon getColor:@"F24545"];
            return;
        }
        self.getVerCodeBtn.enabled = NO;
        [self.getVerCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.getVerCodeBtn setTitle:[NSString stringWithFormat:@"%d秒后重新获取",(int)(timeLast- now)] forState:UIControlStateDisabled];
        self.getVerCodeBtn.backgroundColor = [LCCommon getColor:@"eeeeee"];
        [self.getVerCodeBtn setTitleColor:[LCCommon getColor:@"666666"] forState:UIControlStateNormal] ;
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });
}

- (void)textFieldEdit:(UITextField*)textField{
    if (textField == self.verCodeField) {
        if (![self.alertLabel.text isEqualToString:@""]) {
            [self setAppearWithObject:self.alertLabel hidden:NO];
        }
    }else{
        self.alertLabel.text = @"";
        [self setAppearWithObject:self.alertLabel hidden:YES];
    }
     
     //第几次输入
     NSUInteger targetCursorPosition =[textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
     
     NSString* nStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
     NSString* preTxt = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
     
     char editFlag = 0;
     if (nStr.length <= preTxt.length) {
         editFlag = 0;
         LLog(@"删除第%li个",(long)targetCursorPosition+1);
      }else {
         editFlag = 1;
         LLog(@"增加第%li个",(long)targetCursorPosition+1);
      }
     //当前光标应该在的位置
     NSUInteger curTargetCursorPosition = targetCursorPosition;
     //光标的位置
     UITextPosition* textPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
     [textField setSelectedTextRange:[textField textRangeFromPosition:textPosition toPosition:textPosition]];
}


- (void)setAppearWithObject:(id)sender hidden:(BOOL)hidden{
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.35
                     animations:^{
                         if (sender == self.alertLabel) {
                             if (hidden == NO) {
                                self.alertLabelH.constant = 28;
                             }else if(hidden == YES){
                                self.alertLabelH.constant = 0;
                             }
                         }
                         if (sender == self.topView) {
                             if (hidden == NO) {
                                 self.topViewH.constant = 30;
                             }else if(hidden == YES){
                                 self.topViewH.constant = 0;
                             }
                         }
                         if (sender == self.botView) {
                             if (hidden == NO) {
                                 self.midViewH.constant = midViewAddPhoneH;
                                 self.botViewH.constant = 88;
                                 self.botView.alpha = 1;
                             }else if(hidden == YES){
                                 self.midViewH.constant = midViewNormalH;
                                 self.botViewH.constant = 0;
                                 self.botView.alpha = 0;
                             }
                         }
                         [self.view layoutIfNeeded];
                     }];
}
- (IBAction)cardNumBtn:(UIButton *)sender {
    [self.cardNumField becomeFirstResponder];
}
@end
